package BinarySearchTree;

public class BinarySearchTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root=null;

    //查找二叉搜索树中指定的key
    public TreeNode search(int key) {
        TreeNode cur=root;
        while(cur!=null) {
            if(cur.val<key) {
                cur=cur.right;
            }else if(cur.val>key) {
                cur=cur.left;
            }else {
                return cur;
            }
        }
        return null;
    }

    public void insert(int val) {
        TreeNode node=new TreeNode(val);
        if(root==null) {
            root=node;
            return;
        }
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null) {
            parent=cur;
            if(cur.val<val) {
                cur=cur.right;
            }else if(cur.val>val) {
                cur=cur.left;
            }else {
                return;         //二叉搜索树中不能有相同值的节点
            }
        }
        //parent节点所在的位置就是需要插入的节点父节点
        if(parent.val>val) {
            parent.left=node;
        }else {
            parent.right=node;
        }
    }


    public void remove(int key) {
        TreeNode parent=null;
        TreeNode cur=root;
        while(cur!=null) {
            parent=cur;
            if(cur.val<key) {
                cur=cur.right;
            }else if(cur.val>key) {
                cur=cur.left;
            }else {
                removeNode(parent,cur);
                return;
            }
        }
    }
    private void removeNode(TreeNode parent,TreeNode cur) {
        //1. cur.left==null
        if(cur.left==null) {
            if(cur==root) {
                root=cur.right;
            }else if (cur==parent.left) {
                parent.left=cur.right;
            }else {
                parent.right=cur.right;
            }
        }else if(cur.right==null) {     //2. cur.right==null
            if(cur==root) {
                root=cur.left;
            }else if(cur==parent.left) {
                parent.left=cur.left;
            }else {
                parent.right=cur.left;
            }
        }else {     //3. cur.left!=null && cur.right!=null
            TreeNode target=cur.right;
            TreeNode targetP=cur;
            while(target.left!=null) {
                targetP=target;
                target=target.left;
            }
            //开始替换
            cur.val=target.val;
            if(target==targetP.left) {  //t=tp.left
                targetP.left=target.right;
            }else {                     //t=tp.right
                targetP.right=target.right;
            }
        }




    }
}
